<template>
  <el-card class="box-card">
    <el-button type="primary" icon="Plus" @click="addTrademark">添加品牌</el-button>
    <vue-table style="margin-top: 20px;" :loading="tableLoading" :pageInfo="pageInfo" :tableHeade="tableHeade" :tableData="tableData" :operationList="operationList" :border="false" @operation="operation" @confirmDelete="confirmDelete">
      <template v-slot:default="{ row, head }">
        <div v-if="head === 'logoUrl'">
          <el-image style="width: 100px; height: 100px; border-radius: 10px;" :src="row.logoUrl" fit="fill" />
        </div>
      </template>
    </vue-table>
    <vue-page :pageInfo="pageInfo" @currentChange="currentChange" />
    <el-dialog v-model="dialogVisible" :title="title" width="40%" @close="handleClose">
      <el-form ref="formdata" :rules="rules" :model="form" label-width="auto" label-suffix=":" style="width: 80%; margin-top: 20px;">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="form.tmName" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="fileList">
          <el-upload v-if="dialogVisible" action="#" ref="upload" list-type="picture" :file-list="form.fileList" :on-exceed="handleExceed" :auto-upload="false" class="upload-demo" :on-remove="handleRemove" :on-change="handleSuccess" :limit="1">
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">只可上传jpg/png/gif 且大小不可超过4M</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-bind:loading="btnLoading" @click="handleClose">取消</el-button>
          <el-button type="primary" v-bind:loading="btnLoading" @click="submitForm">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>
<script setup lang="ts">
import {reactive, ref, onMounted } from 'vue'
import type { operationListType, tableDataType } from '@/components/Table/type'
import { reqHasTrademark, reqAddOrUpdateTrademark, reqDeleteTrademark } from '@/api/product/trademark/index'
import type { TrademarkResponseData, Records, Trademark } from '@/api/product/trademark/type'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { uploadImg } from '@/utils/upload'
import { genFileId, ElMessage } from 'element-plus'
onMounted(() => {
  getHasTrademark()
})
let tableHeade = reactive([
  { prop: 'tmName', label: '品牌名称'},
  { prop: 'logoUrl', label: '品牌logo', custom: true},
])
let operationList = reactive([
  { name: '编辑', index: 1, isShow: true},
  { name: '删除', index: 2, color: 'red', isShow: true}
])
let pageInfo = reactive({
  total: 0,
  page: 1,
  limit: 10
})
let tableData = ref<Records>([])
let tableLoading = ref(true)
const getHasTrademark = async () => {
  tableLoading.value = true
  let res: TrademarkResponseData = await reqHasTrademark(pageInfo.page, pageInfo.limit)
  if (res.code === 200) {
    tableData.value = res.data.records
    pageInfo.total = res.data.total
  }
  tableLoading.value = false
}
const operation = (item: operationListType, obj: Trademark) => {
  if (item.index === 1) editTrademark(obj)
}
const currentChange = (e: number) => {
  pageInfo.page = e
  getHasTrademark()
}
const confirmDelete = async (e: tableDataType) => {
  let res = await reqDeleteTrademark(e.id)
  if (res.code === 200) {
    // 根据需求决定是否需要调整当前页码，例如：如当前页只有一条数据删除成功后去上一页
    getHasTrademark()
    ElMessage({ message: '操作成功！', type: 'success' })
  } else {
    ElMessage({ message: '操作失败！', type: 'error' })
  }
}
let dialogVisible = ref(false)
let title = ref('新增品牌')
interface TrademarkPlus extends Trademark {
  fileList: any[]
}
let form = reactive<TrademarkPlus>({
  tmName: '',
  logoUrl: '',
  fileList: []
})
const validatorLogoUrl = (rule: any, value: any, callback: any) => {
  if (value.length > 0) {
    let code = 1
    value[0].raw && (code = beforeUpload(value[0].raw))
    if (code===0) {
      callback(new Error('文件大小不能超过4M,请重新上传！'))
    } else if (code === -1) {
      callback(new Error('上传文件格式不正确,请重新上传！'))
    }
    callback()
  } else {
    callback(new Error('请上传图片！'))
  }
}
const rules = {
  tmName: { required: true, message: '请输入品牌名称！', trigger: 'blur' },
  fileList: {required: true, trigger: 'blur', validator: validatorLogoUrl}
}
let btnLoading = ref(false)
const addTrademark = () => {
  form.tmName = ''
  form.logoUrl = ''
  form.fileList = []
  form.id = undefined
  title.value = '新增品牌'
  dialogVisible.value = true
}
const editTrademark = (trademark: Trademark) => {
  form.tmName = trademark.tmName
  form.logoUrl = trademark.logoUrl
  form.fileList[0] = { url: trademark.logoUrl }
  form.id = trademark.id
  title.value = '编辑品牌'
  dialogVisible.value = true
}
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const beforeUpload = (files: UploadRawFile) => {
  if (files.type === 'image/png' || files.type === 'image/jpeg' || files.type === 'image/gif') {
    if (files.size / 1024 /1024 < 4) return 1
    else {
      upload.value!.clearFiles()
      form.fileList = []
      return 0
    }
  } else {
    upload.value!.clearFiles()
    form.fileList = []
    return -1
  }
}
const handleSuccess = (e: any) => {
  form.fileList[0] = e
}
const handleRemove = (e: any) => {
  form.fileList = []
}
const formdata = ref()
const submitForm = async () => {
  await formdata.value.validate()
  btnLoading.value = true
  if (form.fileList[0].raw) {
    let res = await uploadImg(form.fileList[0].raw)
    if (res.code === 200) {
      form.logoUrl = res.data
      let formD = {
        tmName: form.tmName,
        logoUrl: form.logoUrl,
        id: form.id
      }
      reqAddOrUpdateTrademark(formD).then(res => {
        if(res.code === 200) {
          btnLoading.value = false
          dialogVisible.value = false
          // 编辑成功后留在当前页，新增成功后根据需求判断页码变化
          getHasTrademark()
          ElMessage({ message: '操作成功！', type: 'success' })
        } else {
          btnLoading.value = false
          ElMessage({ message: '操作失败！', type: 'error' })
        }
      })
    }
  } else {
    let formD = {
      tmName: form.tmName,
      logoUrl: form.logoUrl,
      id: form.id
    }
    reqAddOrUpdateTrademark(formD).then(res => {
      if(res.code === 200) {
        btnLoading.value = false
        dialogVisible.value = false
        getHasTrademark()
        ElMessage({ message: '操作成功！', type: 'success' })
      } else {
        btnLoading.value = false
        ElMessage({ message: '操作失败！', type: 'error' })
      }
    })
  }
}
const handleClose = () => {
  dialogVisible.value = false
}
</script>
<style scoped lang="scss">
.el-upload__tip {
  color: red;
}
</style>
